#!/usr/bin/env bash
set -e

##########################
# 辅助函数
##########################
die() { echo -e "\e[31m$*\e[0m" >&2; exit 1; }

##########################
# 0) 检查 root 权限
##########################
if [[ $EUID -ne 0 ]]; then
    die "请使用 root 用户运行本脚本"
fi

##########################
# 1) 安装基础依赖
##########################
apt update -y
apt install -y curl wget jq unzip git ufw software-properties-common

##########################
# 2) 安装 Docker
##########################
if ! command -v docker >/dev/null 2>&1; then
    echo "安装 Docker..."
    curl -fsSL https://get.docker.com | bash
    systemctl enable docker --now
fi

##########################
# 3) 安装 Docker Compose v2
##########################
if ! docker compose version >/dev/null 2>&1; then
    echo "安装 Docker Compose v2..."
    curl -L "https://github.com/docker/compose/releases/download/v2.37.3/docker-compose-$(uname -s)-$(uname -m)" \
        -o /usr/local/bin/docker-compose
    chmod +x /usr/local/bin/docker-compose
fi

##########################
# 4) 获取域名
##########################
API_URL="https://wsuuus.info/v1/get_deploy_domain_name"
resp=$(curl -s "$API_URL") || die "API 请求失败"

mapfile -t domains < <(echo "$resp" | jq -r '.data.data[].website')
(( ${#domains[@]} > 0 )) || die "域名 API 无返回数据"

echo "=== 可选域名 ==="
for i in "${!domains[@]}"; do
    printf "[%02d] %s\n" $((i+1)) "${domains[$i]}"
done

read -rp "请输入 1-${#domains[@]}: " choice
if [[ ! $choice =~ ^[0-9]+$ ]] || (( choice < 1 || choice > ${#domains[@]} )); then
    die "无效域名编号"
fi

DOMAIN=${domains[$((choice-1))]}
echo "已选择域名：$DOMAIN"

##########################
# 5) 配置参数
##########################
CONFIG_FILE="$HOME/.wpinstall_config"
rm -f "$CONFIG_FILE"

MYSQL_ROOT_PASSWORD=$(openssl rand -base64 12 | tr -d '=+/')
MYSQL_USER=wpuser
MYSQL_PASSWORD=$(openssl rand -base64 12 | tr -d '=+/')
MYSQL_DATABASE=wordpress
WP_ADMIN=$(openssl rand -hex 8)
WP_ADMIN_PASS=$(openssl rand -hex 16)
WP_EMAIL="admin@example.com"

cat >> "$CONFIG_FILE" <<EOF
domain:$DOMAIN
MYSQL_ROOT_PASSWORD:$MYSQL_ROOT_PASSWORD
MYSQL_DATABASE:$MYSQL_DATABASE
MYSQL_USER:$MYSQL_USER
MYSQL_PASSWORD:$MYSQL_PASSWORD
admin_user:$WP_ADMIN
admin_password:$WP_ADMIN_PASS
admin_email:$WP_EMAIL
EOF
echo "配置已写入 $CONFIG_FILE"

##########################
# 6) 创建 WordPress 目录
##########################
mkdir -p /data/wp/data/html
mkdir -p /data/wp/data/db
mkdir -p /data/wp/nginx
cd /data/wp

##########################
# 7) Docker Compose 文件
##########################
cat > docker-compose.yml <<EOF
version: "3.8"
services:
  db:
    image: mysql:8.0
    restart: always
    environment:
      MYSQL_ROOT_PASSWORD: $MYSQL_ROOT_PASSWORD
      MYSQL_DATABASE: $MYSQL_DATABASE
      MYSQL_USER: $MYSQL_USER
      MYSQL_PASSWORD: $MYSQL_PASSWORD
    volumes:
      - ./data/db:/var/lib/mysql
    networks:
      - wpnet

  wordpress:
    image: wordpress:php8.2-fpm
    restart: always
    environment:
      WORDPRESS_DB_HOST: db:3306
      WORDPRESS_DB_USER: $MYSQL_USER
      WORDPRESS_DB_PASSWORD: $MYSQL_PASSWORD
      WORDPRESS_DB_NAME: $MYSQL_DATABASE
    volumes:
      - ./data/html:/var/www/html
    networks:
      - wpnet

  wp-nginx:
    image: nginx:latest
    restart: always
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./data/html:/var/www/html
      - ./nginx/default.conf:/etc/nginx/conf.d/default.conf
      - /etc/nginx/certs:/etc/nginx/certs
    depends_on:
      - wordpress
    networks:
      - wpnet

networks:
  wpnet:
EOF

##########################
# 8) 初始 Nginx HTTP 配置
##########################
cat > nginx/default.conf <<EOF
server {
    listen 80;
    server_name $DOMAIN;

    root /var/www/html;
    index index.php index.html;

    location / {
        try_files \$uri \$uri/ /index.php?\$args;
    }

    location ~ \.php\$ {
        fastcgi_pass wordpress:9000;
        fastcgi_index index.php;
        include fastcgi.conf;
        fastcgi_param SCRIPT_FILENAME \$document_root\$fastcgi_script_name;
    }

    # ACME challenge
    location /.well-known/acme-challenge/ {
        root /var/www/html;
    }
}
EOF

##########################
# 9) 启动 WordPress & DB
##########################
docker-compose up -d

##########################
# 10) 安装 wp-cli
##########################
if ! command -v wp >/dev/null 2>&1; then
    wget -q https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar
    chmod +x wp-cli.phar
    mv wp-cli.phar /usr/local/bin/wp
fi

##########################
# 11) 检查域名解析
##########################
SERVER_IP=$(curl -s https://api.ipify.org)
echo "等待域名 $DOMAIN 解析到本服务器 IP: $SERVER_IP"

for i in {1..30}; do
    DOMAIN_IP=$(dig +short $DOMAIN | tail -n1)
    if [[ "$DOMAIN_IP" == "$SERVER_IP" ]]; then
        echo "域名解析成功：$DOMAIN -> $DOMAIN_IP"
        break
    else
        echo "域名未解析到本服务器，等待 10 秒..."
        sleep 10
    fi
    if [[ $i -eq 30 ]]; then
        die "域名解析超时，请检查 DNS 设置"
    fi
done

##########################
# 12) 安装 acme.sh
##########################
if ! command -v acme.sh >/dev/null 2>&1; then
    git clone --depth=1 https://github.com/acmesh-official/acme.sh.git
    cd acme.sh
    ./acme.sh --install -m "ssl@example.com" --auto-upgrade
    cd ..
fi

##########################
# 13) 使用 AWS Route 53 DNS 校验申请证书
##########################
export AWS_ACCESS_KEY_ID="你的AWS_ACCESS_KEY_ID"
export AWS_SECRET_ACCESS_KEY="你的AWS_SECRET_ACCESS_KEY"
export AWS_DEFAULT_REGION="你的AWS_REGION"

acme.sh --issue --dns dns_aws -d "$DOMAIN" \
    --cert-file /etc/nginx/certs/$DOMAIN.crt \
    --key-file /etc/nginx/certs/$DOMAIN.key \
    --reloadcmd "docker-compose exec wp-nginx nginx -s reload" || die "申请证书失败"

##########################
# 14) 配置 Nginx HTTPS
##########################
cat > nginx/default.conf <<EOF
server {
    listen 80;
    server_name $DOMAIN;
    return 301 https://\$host\$request_uri;
}

server {
    listen 443 ssl http2;
    server_name $DOMAIN;

    ssl_certificate     /etc/nginx/certs/$DOMAIN.crt;
    ssl_certificate_key /etc/nginx/certs/$DOMAIN.key;

    root /var/www/html;
    index index.php index.html;

    server_tokens off;
    client_max_body_size 50m;
    add_header X-Frame-Options SAMEORIGIN;
    add_header X-XSS-Protection "1; mode=block";
    add_header X-Content-Type-Options nosniff;

    location / {
        try_files \$uri \$uri/ /index.php?\$args;
    }

    location ~ \.php\$ {
        include fastcgi.conf;
        fastcgi_param SCRIPT_FILENAME \$document_root\$fastcgi_script_name;
        fastcgi_pass wordpress:9000;
    }
}
EOF

docker-compose restart wp-nginx

##########################
# 15) 初始化 WordPress
##########################
docker-compose exec wordpress wp core install \
    --url="https://$DOMAIN" \
    --title="MySite" \
    --admin_user="$WP_ADMIN" \
    --admin_password="$WP_ADMIN_PASS" \
    --admin_email="$WP_EMAIL" \
    --skip-email --allow-root

##########################
# 16) 防火墙
##########################
ufw allow 80
ufw allow 443

echo "====================================="
echo "WordPress 已完成安装！"
echo "访问：https://$DOMAIN"
echo "后台账户：$WP_ADMIN"
echo "后台密码：$WP_ADMIN_PASS"
echo "====================================="

